package edu.ccut.saturn.manager.bundles.core;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.osgi.framework.Bundle;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.component.SaturnDataManager;
import edu.ccut.saturn.core.ServiceFactory;

public class InstallBundle extends DefaultComponent {
	
	private static final String DATA_TYPE = "bundleInfo";
	private static final String NAME_SPACE = "http://edu.ccut.saturn.manager.bundles.core/bundleModule/data";
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		String key = (String) parameterContext.getParameterValue(0);
		String querySql = "select id, symbolicName, name, version, status, bundleFilePath , bundleFileName from bundlesInfo where symbolicName = ?";
		String updateSql = "delete from bundlesInfo where symbolicName = ?";
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		try {
			preparedStatement = parameterContext.getConnection()
					.prepareStatement(querySql);

			preparedStatement.setString(1, key);
			resultSet = preparedStatement.executeQuery();
			SaturnData bundleInfo = SaturnDataManager.getInstance().createData(
					NAME_SPACE, DATA_TYPE);

			if (resultSet.next()) {
				bundleInfo.setString("id", resultSet.getString("id"));
				bundleInfo.setString("key", resultSet.getString("name"));
				bundleInfo.setString("symbolicName", resultSet.getString("symbolicName"));
				bundleInfo.setString("version", resultSet.getString("version"));
				bundleInfo.setString("status", resultSet.getString("status"));
				bundleInfo.setString("bundleFilePath", resultSet.getString("bundleFilePath"));
				bundleInfo.setString("bundleFileName", resultSet.getString("bundleFileName"));
			}
			
			String location = bundleInfo.getString("bundleFilePath") + "\\"
					+ bundleInfo.getString("bundleFileName");

			ServiceFactory.getBundleService().getBundleContext().installBundle(location);
			Bundle[] bundles = ServiceFactory.getBundleService().getBundles();
			for (Bundle bundle : bundles) {
				if (bundle.getSymbolicName().equals(key)) {
					bundle.start();
					break;
				}
			}
			preparedStatement = parameterContext.getConnection()
					.prepareStatement(updateSql);

			preparedStatement.setString(1, key);
			preparedStatement.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (preparedStatement != null) {
				preparedStatement.close();
			}
			if (resultSet != null) {
				resultSet.close();
			}
		}
	}
}